package ldkxingzhe.l365calendar.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import ldkxingzhe.l365calendar.R;

/**
 * 类似ＱＱ的列表选择对话框
 * 从下侧弹出
 * Created by ke on 16-1-30.
 */
public class ListAlertDialogFragment extends DialogFragmentBase implements AdapterView.OnItemClickListener, View.OnClickListener {
    @SuppressWarnings("unused")
    private static final String TAG = "ListAlertDialogFragment";
    private static final String ITEMLIST = "item_list";

    public static final String RESULT = "result";

    private  ArrayList<String> itemList;
    private ListView listView;

    public static ListAlertDialogFragment newInstance(List<String> itemList) {
        if(itemList == null || itemList.size() == 0) return null;
        Bundle args = new Bundle();
        ArrayList<String> arrayList;
        if(itemList instanceof ArrayList){
            arrayList = (ArrayList<String>) itemList;
        }else{
            arrayList = new ArrayList<>(itemList);
        }
        args.putStringArrayList(ITEMLIST, arrayList);
        ListAlertDialogFragment fragment = new ListAlertDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        itemList = args.getStringArrayList(ITEMLIST);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View resultView = inflater.inflate(R.layout.dialog_list_alert, container, false);
        listView = (ListView) resultView.findViewById(R.id.list_view);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), R.layout.list_alert_item, itemList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        resultView.findViewById(R.id.cancel).setOnClickListener(this);
        return resultView;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.list_alert_dialog);
        return getDialog(savedInstanceState);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.putExtra(RESULT, position);
        dismissAndDealWithResult(Activity.RESULT_OK, intent);
    }

    @Override
    public void onClick(View v) {
        dismissAndDealWithResult(Activity.RESULT_CANCELED, null);
    }
}
